<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use app\common\library\Sms;
use fast\Http;
use think\Log;
use think\Db;



/**
 * 会员中心
 */
class User extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third','sendcode'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $url ='https://itunes.apple.com/cn/app/e%E5%9B%9E%E7%A7%9F-%E9%97%B2%E7%BD%AE%E6%89%8B%E6%9C%BA%E9%AB%98%E4%BB%B7%E5%9B%9E%E6%94%B6%E5%B9%B3%E5%8F%B0/id1375412702?mt=8';//app下载地址
        //重定向到指定的URL地址 并且使用302
        $this->redirect($url,302);

//        $this->view->assign('title', __('User center'));
//        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
//        $url = $this->request->request('url');
        $url ='';//app下载地址

        $company_id = $this->request->request('cid')?$this->request->request('cid'):0;

        $company_info = Db::table('cmgd_company')->where('company_id',$company_id)->find();
        $this->view->assign('company_info', $company_info);

        $this->view->assign('companyid', $company_id);

//        if ($this->auth->id)
//            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
//            $username = $this->request->post('username');
            $password = $this->request->post('password');
//            $company_id = $this->request->post('company_id');
            $mobile = $this->request->post('mobile', '');
//            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
//                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,16',
//                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
//                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $username   = $mobile;
            $email      = $password;

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
//                'captcha.require'  => 'Captcha can not be empty',
//                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'company_id'   => $company_id,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);

            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            //判断验证码

            $lastcode =  Sms::get($mobile,'mobileregister');

            $checkresault = Sms::check($mobile,$lastcode['code'],'mobileregister');

            if(!$checkresault){
                $this->error('短信验证码错误', null, ['token' => $this->request->token()]);
            }

            if ($this->auth->register($username, $password, $email, $mobile,array('company_id' => $company_id))) {

//              注册成功后post到e回租，返回成功后，增加e回租userid到用户表

                $regdate = array(
                    'mobile'    =>  $mobile,
                    'vcode'     =>  $lastcode['code'],
                    'noteToken' =>  $lastcode['noteToken'],
                    'beginPassword'=> strtoupper(md5($password))
                );
                $reg_url = 'http://ehuizuapi.fcity.xin/AppService/permit/regist';
                $reg_ehz = Http::sendRequest($reg_url,$regdate);
//                Log::info($reg_ehz);
                $reg_ehz = json_decode($reg_ehz['msg'],true);

                if($reg_ehz['code'] == 0){
//                    Log::info($this->auth->id);
//                    Log::alert($reg_ehz['data']['userId']);
//                  $reg_ehz['data']['userId'];
//                    $user = User::get($this->auth->id);
                    Db::table('cmgd_user')->where('id',$this->auth->id)->update(['bio' => $reg_ehz['data']['userId']]);
//                    $user->bio = $reg_ehz['data']['userId'];
//                    $user->save();

                    $this->success(__('Sign up successful') , $url ? $url : url('user/index'));
                }else{
                    $this->error('e回租注册失败', null, ['token' => $this->request->token()]);
                }

                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                 $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {


        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        $this->success(__('Logout successful') . $synchtml, url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogout();
                }
                $this->success(__('Reset password successful') . $synchtml, url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    /**
     * 发送e回租验证码
     */
    public function sendcode()
    {
        $mobile = input('mobile');

        $ehzurl = 'http://ehuizuapi.fcity.xin/AppService/permit/common/sendVcode';
        $date['type']   = '2';
        $date['mobile'] = $mobile;
        $resault = Http::sendRequest($ehzurl,$date);

        if($resault['ret']){

            $resaultmsg =  json_decode($resault['msg'],true);
//            echo $resaultmsg['code'];

            if($resaultmsg['code'] == 0) {
//                echo $resaultmsg['data']['noteToken'];
//                echo $resaultmsg['data']['vcode'];
                $resault = Sms::send_ehz($mobile,$resaultmsg['data']['vcode'],$resaultmsg['data']['noteToken'], 'mobileregister');
                echo $resaultmsg['message'];
//                $url = 'http://www.baidu.com';
//                $this->success($resaultmsg['message'], $url);
            }else{
                echo $resaultmsg['message'];
//                $this->error($resaultmsg['message'], null, ['token' => $this->request->token()]);
//                return FALSE;
            }
        }


//        array(2) {
//        ["ret"] => bool(true)
//        ["msg"] => string(77) "{"code":"1001","message":"非法请求","data":"输入的手机号不合法"}"
//}

//        array(2) {
//        ["ret"] => bool(true)
//        ["msg"] => string(59) "{"code":"1013","message":"该手机号已注册","data":""}"
//}

//        array(2) {
//        ["ret"] => bool(true)
//        ["msg"] => string(238) "{"code":"0","message":"处理成功","data":{"noteToken":"94697D01C920AB2B2FA517BE72487BB38A78BD430170E7808C8E3DED4AE30E1552A1F7337C48C4E5D1F62D4E6572B48D6965BFD59F877FC44B26BFB4558C9C25A2DA8812251FE0D953B5C7648747AA89","vcode":"627745"}}"
//}


    }
}


